package org.example.controller.backup;

import cn.hutool.core.bean.BeanUtil;
import org.example.common.result.ResponseData;
import org.example.flowable.handler.ProcessHandler;
import org.example.repository.model.DeploymentVO;
import org.flowable.engine.repository.Deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.zip.ZipInputStream;

/**
 * 部署流程定义
 */
@RestController
@RequestMapping("api/flow/process")
public class ProcessController {
    @Autowired
    private ProcessHandler processHandler;


    @RequestMapping(value = "/deploy/files/zip", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
    @ResponseBody
    public ResponseData deployByZip(String name, String category, String tenantId, MultipartFile file) {
        Deployment deployment = null;
        try (ZipInputStream zipIn = new ZipInputStream(file.getInputStream(), Charset.forName("UTF-8"))) {
            deployment = processHandler.deploy(name, category, tenantId, zipIn);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //忽略二进制文件（模板文件、模板图片）返回
        DeploymentVO deploymentVO = BeanUtil.copyProperties(deployment,DeploymentVO.class,"resources");
        return ResponseData.success(deploymentVO);
    }


    /**
     * 部署流程定义
     */
    @ResponseBody
    @RequestMapping(value = "/deploy/file", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
    public ResponseData<DeploymentVO> deployByInputStream(String name, String tenantId, String category, MultipartFile file) {
        Deployment deploy = null;
        if (processHandler.exist(name)) {
            deploy = processHandler.deployName(name);
        } else {
            try (InputStream in = file.getInputStream()) {
                deploy = processHandler.deploy(name, tenantId, category, in);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //忽略二进制文件（模板文件、模板图片）返回
        DeploymentVO deploymentVO = BeanUtil.copyProperties(deploy, DeploymentVO.class, "resources");
        return ResponseData.success(deploymentVO);
    }
}

